//
//  OrderViewController.m
//  danpin
//
//  Created by chuangjia on 27/10/2015.
//  Copyright © 2015 chuangjia. All rights reserved.
//

#import "OrderViewController.h"
#import "UserAdressViewController.h"
#import "TTTAttributedLabel.h"
#import "AlipayHeader.h"
#import "AppDelegate.h"
#import "QKInfoCard.h"
#import "UILabel+StringFrame.h"
#import "SlidingViewManager.h"
#import "UMengShare.h"

#import "BottomToolBar.h"


@interface OrderViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,UIAlertViewDelegate,OrderDelegate>
{
    
}
@property(nonatomic,strong) NSMutableDictionary *addressDictionary;
@property(nonatomic,strong) UITableView *tbView;
@property(nonatomic,strong) NSMutableArray *sectionArray;
@property(nonatomic,strong) UITextField     *txtBeizhu;
@property(nonatomic,strong) UITextField     *txtQuan;
@property(nonatomic,strong) UIButton *helpDp;
//
@property(nonatomic,strong) BottomToolBar *bottomToolView;
@property(nonatomic,strong) TTTAttributedLabel *lbPrice;
@property(nonatomic,strong) UISwitch * jifenSwitch;
@property(nonatomic,strong) UISwitch * balanceSwitch;
@property(nonatomic,strong) UISwitch * zhekouquanSwitch;
@property(nonatomic,strong) NSString *out_trade_no;
@property(nonatomic,strong) NSMutableDictionary *zhifuDictionary; //支付后的信息

//
//@property(nonatomic,strong)SlidingViewManager *svmanger;
@property(nonatomic,strong) UIView *svmanger;
@property(nonatomic,strong) OrderPriceListView *priceListView;
///
@property(nonatomic,strong) NSMutableDictionary *orderinfoDictionary; //订单信息
@property(nonatomic,strong) NSMutableDictionary *userinfoDictionary; //用户信息
@property(nonatomic,strong) NSMutableDictionary *agreementinfoDictionary; //帮助信息
@property(nonatomic,strong) NSMutableDictionary *dpCodeDictionary; //优惠码
@end

@implementation OrderViewController
@synthesize addressDictionary=_addressDictionary;
@synthesize tbView =_tbView;
@synthesize sectionArray=_sectionArray;
@synthesize txtBeizhu=_txtBeizhu;
@synthesize txtQuan=_txtQuan;
@synthesize bottomToolView=_bottomToolView;
@synthesize lbPrice=_lbPrice;
@synthesize jifenSwitch=_jifenSwitch;
@synthesize balanceSwitch=_balanceSwitch;
@synthesize zhekouquanSwitch=_zhekouquanSwitch;
@synthesize orderInfo=_orderInfo;
@synthesize out_trade_no=_out_trade_no;
@synthesize helpDp=_helpDp;
@synthesize zhifuDictionary=_zhifuDictionary;
@synthesize svmanger=_svmanger;
@synthesize type=_type;
@synthesize dpCodeDictionary=_dpCodeDictionary;
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navTitle =@"确认订单";
    if (!_sectionArray) {
        _sectionArray =[[NSMutableArray alloc] init];
    }
    _sectionArray = [NSMutableArray arrayWithObjects:@"address",@"orderinfo",@"zhifu",@"beizhu",@"buyintro", nil];
    if (!_addressDictionary) {
        _addressDictionary = [[NSMutableDictionary alloc] init];
    }
    _addressDictionary = (NSMutableDictionary*)[ZShare sharedInstance].defaultAddress;
    
    if (!_zhifuDictionary) {
        _zhifuDictionary = [[NSMutableDictionary alloc] init];
    }
    [self initdata];
    [self initUI];
    [self initBottomView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHasShowed:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateAddress) name:@"deleteAddressList" object:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
   
}
-(void)updateAddress
{
    if ([self isLogin]) {
        [self getDefaultaddress];
    }
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    AppDelegate *app = [[UIApplication sharedApplication]delegate];
    app.orderDelegate=nil;
    self.tbView =nil;
//    self.svmanger=nil;
    self.jifenSwitch=nil;
    self.balanceSwitch=nil;
    self.zhekouquanSwitch=nil;
    if(_svmanger)
    {
        [_svmanger removeFromSuperview];
        _svmanger = nil;
    }
    
    
    if(_priceListView)
    {
        [_priceListView removeFromSuperview];
        _priceListView = nil;
    }
    self.addressDictionary =nil;
    self.sectionArray=nil;
    self.txtBeizhu=nil;
    self.txtQuan = nil;
    self.helpDp = nil;
    self.bottomToolView=nil;
    self.lbPrice =nil;
    self.out_trade_no =nil;
    self.zhifuDictionary = nil;
    self.orderinfoDictionary = nil;
    self.userinfoDictionary=nil;
    self.agreementinfoDictionary=nil;
    DLog(@"%s", __PRETTY_FUNCTION__);
}
-(void)initdata
{
     _out_trade_no=@"";

    if(!_orderinfoDictionary)
    {
        _orderinfoDictionary =[[NSMutableDictionary alloc] init];
    }
    
    [_orderinfoDictionary setValue:_orderInfo.strDim forKey:@"dimsInfo"];
    [_orderinfoDictionary setValue:_orderInfo.strProductImageURL forKey:@"image"];
    [_orderinfoDictionary setValue:_orderInfo.strProduct forKey:@"title"];
    [_orderinfoDictionary setValue:[NSString stringWithFormat:@"%.0f",_orderInfo.fPrice] forKey:@"price"];
    [_orderinfoDictionary setValue:[NSString stringWithFormat:@"%d",_orderInfo.nQty] forKey:@"qty"];
    [_orderinfoDictionary setValue:_orderInfo.webName forKey:@"siteName"];
    [_orderinfoDictionary setValue:[NSString stringWithFormat:@"%.0f",_orderInfo.fFareFeeUSA] forKey:@"shipFeeLocal"];
    [_orderinfoDictionary setValue:[NSString stringWithFormat:@"%.0f", _orderInfo.fFareFee] forKey:@"shipFeeOverseas"];
    [_orderinfoDictionary setValue:[NSString stringWithFormat:@"%.0f", _orderInfo.taxPrice] forKey:@"taxPrice"];
    [_orderinfoDictionary setValue:[NSString stringWithFormat:@"%.0f", _orderInfo.conversionFee] forKey:@"conversionFee"];
    [_orderinfoDictionary setValue:_orderInfo.strWeightUnit forKey:@"weightKg"];
    [_orderinfoDictionary setValue:_orderInfo.strWeightUnit forKey:@"weightUnit"];
    [_orderinfoDictionary setValue:[NSString stringWithFormat:@"%.0f", _orderInfo.fTotalPrice] forKey:@"totalPrice"];
  
    if(!_userinfoDictionary)
    {
        _userinfoDictionary =[[NSMutableDictionary alloc] init];
    }
    if(!_agreementinfoDictionary)
    {
        _agreementinfoDictionary =[[NSMutableDictionary alloc] init];
    }
     if ([self isLogin]) {
        [self getDefaultaddress];
        [self getUserScore];
     }
    
}
//=================================================
//
//=================================================

- (void)keyboardWillChangeFrame:(NSNotification *)notification
{
    
    NSDictionary *userInfo = notification.userInfo;
    // 键盘的frame
    CGRect keyboardF = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGSize keyboardSize = keyboardF.size;
    _tbView.frame = CGRectMake(0, hightAuto(65), self.view.bounds.size.width, self.view.bounds.size.height - hightAuto(65) - 45 - keyboardSize.height);
    _bottomToolView.frame = CGRectMake(0, self.view.frame.size.height-45 - keyboardSize.height, self.view.frame.size.width, 45);
    
    
}
- (void)keyboardWasHidden:(NSNotification *)notification
{
    _tbView.frame = CGRectMake(0, hightAuto(65), self.view.bounds.size.width, self.view.bounds.size.height - hightAuto(65) - 45);
    _bottomToolView.frame = CGRectMake(0, self.view.frame.size.height-45, self.view.frame.size.width, 45);
}
- (void)keyboardHasShowed:(NSNotification *)notification
{
    
}

-(void)keyboardHide:(UITapGestureRecognizer*)tap
{
    if(self.txtBeizhu && [self.txtBeizhu isFirstResponder])
    {
        [self.txtBeizhu resignFirstResponder];
    }
    
    if(self.txtQuan && [self.txtQuan isFirstResponder])
    {
        [self.txtQuan resignFirstResponder];
    }
    
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField==self.txtBeizhu) {
        [self.txtQuan becomeFirstResponder];
    }else if (textField==self.txtQuan)
    {
        [textField resignFirstResponder];
    }else{
        [textField resignFirstResponder];
    }
    
    return YES;
}
//=================================================
//
//=================================================
-(void)initUI
{
    _tbView = [[UITableView alloc] initWithFrame:CGRectMake(0, hightAuto(65), self.view.bounds.size.width, self.view.bounds.size.height-hightAuto(65)-45) style:UITableViewStyleGrouped];
    _tbView.delegate = self;
    _tbView.dataSource = self;
    _tbView.backgroundColor =[UIColor colorWithRed:0.937 green:0.937 blue:0.937 alpha:1];
    _tbView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    _tbView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:_tbView];
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
    //设置成NO表示当前控件响应后会传播到其他控件上，默认为YES。
    tapGestureRecognizer.cancelsTouchesInView = NO;
    //将触摸事件添加到当前view
    [self.view addGestureRecognizer:tapGestureRecognizer];
    tapGestureRecognizer=nil;
    
}
#pragma mark - tableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [_sectionArray count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSString *sectionTitle =[self.sectionArray objectAtIndex:section];
    if ([sectionTitle isEqualToString:@"address"])
    {
         return 1;
    }else  if ([sectionTitle isEqualToString:@"orderinfo"])
    {
         return 1;
    }else  if ([sectionTitle isEqualToString:@"zhifu"])
    {
         return 1;
    }else  if ([sectionTitle isEqualToString:@"beizhu"])
    {
         return 5;
    }else  if ([sectionTitle isEqualToString:@"buyintro"])
    {
         return 1;
    }
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 15;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *sectionTitle =[self.sectionArray objectAtIndex:indexPath.section];
    if ([sectionTitle isEqualToString:@"address"])
    {
        return [OrderAddressCell returnCellHeight:_addressDictionary];
        
    }else  if ([sectionTitle isEqualToString:@"orderinfo"])
    {
         return [OrderInfoCell returnCellHeight:self.orderInfo];
        
    }else  if ([sectionTitle isEqualToString:@"zhifu"])
    {
        return [OrderZhifuCell returnCellHeight:@""];
    }else  if ([sectionTitle isEqualToString:@"beizhu"])
    {
        return 40;
    }else  if ([sectionTitle isEqualToString:@"buyintro"])
    {
        return [OrderBuyIntroCell returnCellHeight:nil];
    }
    return 0;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = (UITableViewCell*)[tableView  dequeueReusableCellWithIdentifier:@""];
    NSString *sectionTitle =[self.sectionArray objectAtIndex:indexPath.section];
    if ([sectionTitle isEqualToString:@"address"])
    {
        OrderAddressCell *cell = (OrderAddressCell*)[tableView  dequeueReusableCellWithIdentifier:@"OrderAddressCell"];
        if(cell == nil)
        {
            cell = [[OrderAddressCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
            cell.backgroundColor=[UIColor whiteColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            __weak typeof (self) wSelf = self;
            [cell setCallBack:^(BEventType t, UIView *v,id obj,id key,NSIndexPath *indexPath) {
                [wSelf cellAction:t views:v obj:obj key:key indexPath:indexPath];
            }];
        }
        [cell showInfo:_addressDictionary key:@"OrderAddressCell" indexPath:indexPath];
        return cell;
    }else  if ([sectionTitle isEqualToString:@"orderinfo"])
    {
        OrderInfoCell *cell = (OrderInfoCell*)[tableView  dequeueReusableCellWithIdentifier:@"OrderInfoCell"];
        if(cell == nil)
        {
            cell = [[OrderInfoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
            cell.backgroundColor=[UIColor whiteColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            __weak typeof (self) wSelf = self;
            [cell setCallBack:^(BEventType t, UIView *v,id obj,id key,NSIndexPath *indexPath) {
                [wSelf cellAction:t views:v obj:obj key:key indexPath:indexPath];
            }];
        }
        [cell showInfo:_orderinfoDictionary key:@"OrderInfoCell" indexPath:indexPath];
        return cell;
    }else  if ([sectionTitle isEqualToString:@"zhifu"])
    {
        OrderZhifuCell *cell = (OrderZhifuCell*)[tableView  dequeueReusableCellWithIdentifier:@"OrderZhifuCell"];
        if(cell == nil)
        {
            cell = [[OrderZhifuCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
            cell.backgroundColor=[UIColor whiteColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            __weak typeof (self) wSelf = self;
            [cell setCallBack:^(BEventType t, UIView *v,id obj,id key,NSIndexPath *indexPath) {
                [wSelf cellAction:t views:v obj:obj key:key indexPath:indexPath];
            }];
        }
        [cell showInfo:_addressDictionary key:@"OrderZhifuCell" indexPath:indexPath];
        return cell;
        
    }else  if ([sectionTitle isEqualToString:@"beizhu"])
    {
        if(cell == nil)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
            cell.backgroundColor=[UIColor whiteColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        if (indexPath.row==0){
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            self.txtBeizhu.frame =CGRectMake(PHOTO_FRAME_WIDTH, 2, DEVICE_WIDTH-PHOTO_FRAME_WIDTH*2, 40);
            NSString *coupon = [[ZShare sharedInstance].zhekouquan replaceNullString];
            if (coupon.length>0) {
                self.txtBeizhu.text = coupon;
            }
            [cell addSubview:self.txtBeizhu];
            return cell;
        }else if (indexPath.row==1) {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            self.txtQuan.frame =CGRectMake(PHOTO_FRAME_WIDTH, 2, DEVICE_WIDTH-PHOTO_FRAME_WIDTH*2, 40);
            [cell addSubview:self.txtQuan];
           
        }else if (indexPath.row==2) {
            float fLeft = PHOTO_FRAME_WIDTH;
            
            UILabel* left = [[UILabel alloc]initWithFrame:CGRectMake(fLeft, 0, DEVICE_WIDTH, 40)];
            left.textColor = TITLE_COLOR;
            left.font = FONT(13);
            left.text = @"如折扣码无法使用, 原价下单";
            [left sizeToFit];
            [cell addSubview:left];
            
            left.frame = CGRectMake(fLeft, 0, left.frame.size.width, 40);
            
            UIButton *gjhelpbtn =[UIButton buttonWithType:UIButtonTypeCustom];
            gjhelpbtn.backgroundColor = [UIColor clearColor];
            [gjhelpbtn setImage:[UIImage imageNamed:@"help.png"] forState:UIControlStateNormal];
            gjhelpbtn.frame =CGRectMake(left.frame.size.width+left.frame.origin.x+PHOTO_FRAME_WIDTH,(40-16)/2, 16, 16);
            [gjhelpbtn addTarget:self action:@selector(zhekouquanHelp) forControlEvents:UIControlEventTouchUpInside];
            [cell addSubview:gjhelpbtn];
            if(!_zhekouquanSwitch)
            {
                _zhekouquanSwitch = [[UISwitch alloc]initWithFrame:CGRectMake(DEVICE_WIDTH - 50, PHOTO_TIME_PADDING, 50, 20)];
                _zhekouquanSwitch.tag = 0;
                [_zhekouquanSwitch sizeToFit];
                _zhekouquanSwitch.onTintColor = [UIColor blackColor];
                [_zhekouquanSwitch addTarget:self action:@selector(switchIsChanged:) forControlEvents:UIControlEventValueChanged];
                
            }
            _zhekouquanSwitch.frame = CGRectMake(DEVICE_WIDTH - PHOTO_FRAME_WIDTH - _zhekouquanSwitch.bounds.size.width,
                                              (40 - _zhekouquanSwitch.bounds.size.height)/2,
                                              _zhekouquanSwitch.bounds.size.width, _zhekouquanSwitch.bounds.size.height) ;
            [cell addSubview:_zhekouquanSwitch];
            
        }else if (indexPath.row==3) {
            float fLeft = PHOTO_FRAME_WIDTH;
            
            UILabel* left = [[UILabel alloc]initWithFrame:CGRectMake(fLeft, 0, DEVICE_WIDTH, 40)];
            left.textColor = TITLE_COLOR;
            left.font = FONT(13);
            left.text = @"余额: ";
            [left sizeToFit];
            [cell addSubview:left];
            
            left.frame = CGRectMake(fLeft, 0, left.frame.size.width, 40);
            
            fLeft += left.frame.size.width + PHOTO_TIME_PADDING;
            
            //积分数值
            UILabel* lbJifen = [[UILabel alloc]initWithFrame:CGRectMake(fLeft, 0, DEVICE_WIDTH, 40)];
            lbJifen.textColor = CONTEXT_COLOR;
            lbJifen.font = FONT(13);
           
            NSString *balance =@"0";
            if (_userinfoDictionary) {
                balance =[[NSString stringWithFormat:@"%@",[_userinfoDictionary objectForKey:@"user_balance"]] replaceNullString];
            }
            
            if([balance intValue] > 0)
                lbJifen.text = [NSString stringWithFormat:@"可用%@元 ", balance];//todo: 需要每次提交订单的时候，获取可用的有效积分。注意积分安全。
            else
            {
                lbJifen.text = @"暂无余额";
            }
            [lbJifen sizeToFit];
            [cell addSubview:lbJifen];
            
            lbJifen.frame = CGRectMake(fLeft, 0, lbJifen.frame.size.width, 40);
            fLeft += lbJifen.frame.size.width + PHOTO_TIME_PADDING;
            
             if(!_balanceSwitch)
             {
                 _balanceSwitch = [[UISwitch alloc]initWithFrame:CGRectMake(DEVICE_WIDTH - 50, PHOTO_TIME_PADDING, 50, 20)];
                 _balanceSwitch.tag = 1;
                  [_balanceSwitch sizeToFit];
                 _balanceSwitch.onTintColor = [UIColor blackColor];
                 [_balanceSwitch addTarget:self action:@selector(switchIsChanged:) forControlEvents:UIControlEventValueChanged];
                 
             }
           
            if ([balance floatValue]==0) {
                _balanceSwitch.enabled =NO;
            }else{
                _balanceSwitch.enabled = YES;
            }
           
            _balanceSwitch.frame = CGRectMake(DEVICE_WIDTH - PHOTO_FRAME_WIDTH - _balanceSwitch.bounds.size.width,
                                            (40 - _balanceSwitch.bounds.size.height)/2,
                                            _balanceSwitch.bounds.size.width, _balanceSwitch.bounds.size.height) ;
            [cell addSubview:_balanceSwitch];
            
        }else if (indexPath.row==4) {
            float fLeft = PHOTO_FRAME_WIDTH;
            
            UILabel* left = [[UILabel alloc]initWithFrame:CGRectMake(fLeft, 0, DEVICE_WIDTH, 40)];
            left.textColor = TITLE_COLOR;
            left.font = FONT(13);
            left.text = @"积分: ";
            [left sizeToFit];
            [cell addSubview:left];
            
            left.frame = CGRectMake(fLeft, 0, left.frame.size.width, 40);
            
            fLeft += left.frame.size.width + PHOTO_TIME_PADDING;
            
            //积分数值
            UILabel* lbJifen = [[UILabel alloc]initWithFrame:CGRectMake(fLeft, 0, DEVICE_WIDTH, 40)];
            lbJifen.textColor = CONTEXT_COLOR;
            lbJifen.font = FONT(13);
            // lbJifen.
            NSString *jifen =@"0";
            if (_userinfoDictionary) {
                jifen =[[NSString stringWithFormat:@"%@",[_userinfoDictionary objectForKey:@"score_dk_fee_max"]] replaceNullString];
            }
            lbJifen.text = [NSString stringWithFormat:@"可抵%@元 ", jifen];//todo: 需要每次提交订单的时候，获取可用的有效积分。注意积分安全。
            [lbJifen sizeToFit];
            [cell addSubview:lbJifen];
            
            lbJifen.frame = CGRectMake(fLeft, 0, lbJifen.frame.size.width, 40);
            fLeft += lbJifen.frame.size.width + PHOTO_TIME_PADDING;
            
            //积分如何获得，给用户一个弹出层，告诉用户，每天登陆、爆料、发帖子就有内容
            UIButton *buyBtn =[UIButton buttonWithType:UIButtonTypeCustom];
            buyBtn.tag = 2;
            buyBtn.backgroundColor = [UIColor clearColor];
            [buyBtn setImage:[UIImage imageNamed:@"help.png"] forState:UIControlStateNormal];
            buyBtn.frame =CGRectMake(fLeft,(40-16)/2, 16, 16);
            [buyBtn addTarget:self action:@selector(clickHelpEvent) forControlEvents:UIControlEventTouchUpInside];
            [cell addSubview:buyBtn];
            if (!_jifenSwitch) {
                _jifenSwitch = [[UISwitch alloc]initWithFrame:CGRectMake(DEVICE_WIDTH - 50, PHOTO_TIME_PADDING, 50, 20)];
                _jifenSwitch.tag =2;
                [_jifenSwitch sizeToFit];
                _jifenSwitch.onTintColor = [UIColor blackColor];
                [_jifenSwitch addTarget:self action:@selector(switchIsChanged:) forControlEvents:UIControlEventValueChanged];
                
            }
            if ([jifen floatValue]==0) {
                _jifenSwitch.enabled =NO;
            }else{
                _jifenSwitch.enabled = YES;
            }
           
            _jifenSwitch.frame = CGRectMake(DEVICE_WIDTH - PHOTO_FRAME_WIDTH - _jifenSwitch.bounds.size.width,
                                            (40 - _jifenSwitch.bounds.size.height)/2,
                                            _jifenSwitch.bounds.size.width, _jifenSwitch.bounds.size.height) ;
           [cell addSubview:_jifenSwitch];
            
        }
        return cell;
        
    }else  if ([sectionTitle isEqualToString:@"buyintro"])
    {
        OrderBuyIntroCell *cell = (OrderBuyIntroCell*)[tableView  dequeueReusableCellWithIdentifier:@"OrderBuyIntroCell"];
        if(cell == nil)
        {
            cell = [[OrderBuyIntroCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
            cell.backgroundColor=[UIColor whiteColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            __weak typeof (self) wSelf = self;
            [cell setCallBack:^(BEventType t, UIView *v,id obj,id key,NSIndexPath *indexPath) {
                [wSelf cellAction:t views:v obj:obj key:key indexPath:indexPath];
            }];
        }
        [cell showInfo:_agreementinfoDictionary key:@"OrderBuyIntroCell" indexPath:indexPath];
        return cell;
    }
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSString *sectionTitle =[self.sectionArray objectAtIndex:indexPath.section];
    if ([sectionTitle isEqualToString:@"address"])
    {
        if ([self isLogin])
        {
            UserAdressViewController *useraddress =[[UserAdressViewController alloc] init];
            useraddress.type =1;
            [useraddress setSelectedCallBack:^(id key, id v) {
                NSDictionary *dict  = (NSDictionary *)key;
                _addressDictionary = [NSMutableDictionary dictionaryWithDictionary:dict];
                [_tbView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
            }];
            [self.navigationController pushViewController:useraddress animated:YES];
        }
        
    }else  if ([sectionTitle isEqualToString:@"beizhu"])
    {
        if(indexPath.row==0) //备注
        {
            OrderBeiZhuViewController *beizhu = [[OrderBeiZhuViewController alloc] init];
            NSString *coupon = [[ZShare sharedInstance].zhekouquan replaceNullString];
            beizhu.conpon = coupon;
            __weak typeof (self) wSelf = self;
            [beizhu setCallBack:^(UIView *v, id o) {
                if (o && [o isKindOfClass:[NSString class]]) {
                    wSelf.txtBeizhu.text = o;
                }
            }];
            [self.navigationController pushViewController:beizhu animated:YES];
            beizhu=nil;
            return;
            
        }else if(indexPath.row==1)//优惠码
        {
            OrderDiscountViewController *discount = [[OrderDiscountViewController alloc] init];

            NSString *totalPrice =[[NSString stringWithFormat:@"%@",[_orderinfoDictionary objectForKey:@"totalPrice"]] replaceNullString];
            discount.totalfee  =totalPrice;
            __weak typeof (self) wSelf = self;
            [discount setCallBack:^(UIView *v, id o) {
                
                if (o && [o isKindOfClass:[NSDictionary class]]) {
                    NSString *msg = [[NSString stringWithFormat:@"%@",[o objectForKey:@"msg"]] replaceNullString];
                    if (msg.length>0) {
                         wSelf.txtQuan.text = msg;
                    }
                    wSelf.dpCodeDictionary = [NSMutableDictionary dictionaryWithDictionary:o];
                    if (_balanceSwitch && _jifenSwitch) {
                        [_balanceSwitch setOn:NO animated:YES];
                        [_jifenSwitch setOn:NO animated:YES];
                    }
                    [wSelf updateTotalFee:0];
                }
            }];
            [self.navigationController pushViewController:discount animated:YES];
            discount = nil;
            return;
        }
    }
}
-(void)cellAction:(BEventType)type views:(UIView *)v obj:(id)obj key:(id)key indexPath:(NSIndexPath *)indexPath
{
    switch (type) {
        case BEventType_help:
        {
            NSString *str = (NSString*)key;
            [self clickHelpEvent:str];
        }
            break;
        case BEventType_agreement:
        {
            NSString *link = @"";
            NSString *title = @"";
            NSArray *agreent = [_agreementinfoDictionary objectForKey:@"help_agreement"];
            if ([key isEqualToString:@"danpin1"]) {
                title =@"服务协议";
            }else if ([key isEqualToString:@"danpin2"]) {
                 title =@"退换协议";
            }else if ([key isEqualToString:@"danpin3"]) {
                 title =@"隐私协议";
            }
            for (NSDictionary *dict in agreent) {
                NSString *mtitle = [dict objectForKey:@"title"];
                if ([mtitle isEqualToString:title]) {
                    link = [dict objectForKey:@"link"];
                    break;
                }
            }
            OrderTaxViewController *tax =[[OrderTaxViewController alloc] init];
            tax.urlStr = link;
            tax.titleStr = title;
            [self.navigationController pushViewController:tax animated:YES];
            tax=nil;
            return;
        }
            break;
        default:
            break;
    }
}
-(void)zhekouquanHelp
{
     [self clickHelpEvent:@"5"];
}
-(void)clickHelpEvent
{
    [self clickHelpEvent:@"3"];
}

- (void) switchIsChanged:(UISwitch *)paramSender{
   
    UISwitch *switchTag = (UISwitch*)paramSender;
    if (switchTag.tag !=0) {
        if ([paramSender isOn]){
            [self updateTotalFee:switchTag.tag];
        } else
        {
            [self updateTotalFee:0];
        }
    }
//    NSLog(@"switchIsChanged is = %ld", (long)switchTag.tag);
   
}
//=================================================
//
//=================================================
-(UITextField *)txtBeizhu
{
    if (!_txtBeizhu) {
        UILabel* left = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 10, 40)];
        left.textColor = TITLE_COLOR;
        left.font = FONT(13);
        left.text = @"备注:  ";
        [left sizeToFit];
        
        self.txtBeizhu = [[UITextField alloc] initWithFrame:CGRectZero];
        self.txtBeizhu.textColor =[UIColor lightGrayColor];
        self.txtBeizhu.leftViewMode = UITextFieldViewModeAlways;
        self.txtBeizhu.leftView = left;
        [self.txtBeizhu setBorderStyle:UITextBorderStyleNone];
        self.txtBeizhu.clearButtonMode = UITextFieldViewModeWhileEditing;
        self.txtBeizhu.font = FONT(13);
        self.txtBeizhu.enabled = NO;
        self.txtBeizhu.placeholder =@"可填写商家折扣码/优惠券";
        self.txtBeizhu.autocorrectionType = UITextAutocorrectionTypeNo;
        self.txtBeizhu.autocapitalizationType = UITextAutocapitalizationTypeNone;
        self.txtBeizhu.returnKeyType = UIReturnKeyNext;
        self.txtBeizhu.keyboardType =UIKeyboardTypeDefault;
//        self.txtBeizhu.delegate=self;
        [self.txtBeizhu setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
        [self.txtBeizhu setValue:FONT(13) forKeyPath:@"_placeholderLabel.font"];
    }
    return _txtBeizhu;
}
-(UITextField *)txtQuan
{
    if (!_txtQuan) {
        UILabel* left = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 10, 40)];
        left.textColor = TITLE_COLOR;
        left.font = FONT(13);
        left.text = @"优惠券:  ";
        [left sizeToFit];
        self.txtQuan = [[UITextField alloc] initWithFrame:CGRectZero];
        self.txtQuan.textColor =[UIColor lightGrayColor];
        self.txtQuan.leftViewMode = UITextFieldViewModeAlways;
        self.txtQuan.leftView = left;
        [self.txtQuan setBorderStyle:UITextBorderStyleNone];
        self.txtQuan.clearButtonMode = UITextFieldViewModeWhileEditing;
        self.txtQuan.font = FONT(13);
        self.txtQuan.enabled = NO;
        self.txtQuan.placeholder =@"暂无优惠券";
        self.txtQuan.autocorrectionType = UITextAutocorrectionTypeNo;
        self.txtQuan.autocapitalizationType = UITextAutocapitalizationTypeNone;
        self.txtQuan.returnKeyType = UIReturnKeyDone;
        self.txtQuan.keyboardType =UIKeyboardTypeDefault;
//        self.txtQuan.delegate=self;
        [self.txtQuan setValue:[UIColor lightGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
        [self.txtQuan setValue:FONT(13) forKeyPath:@"_placeholderLabel.font"];
    }
    return _txtQuan;
}



//=================================================
//
//=================================================
-(void)initBottomView
{
    if (_bottomToolView) {
        [_bottomToolView removeFromSuperview];
        _bottomToolView=nil;
    }
    _bottomToolView =[[BottomToolBar alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-45, self.view.frame.size.width, 45)];
    _bottomToolView.backgroundColor=DARK_BACKGROUND_COLOR;
    [self.view addSubview:_bottomToolView];
    
    
    UIButton *newdp =[UIButton buttonWithType:UIButtonTypeCustom];
    newdp.tag=0;
    newdp.frame =CGRectMake(self.view.frame.size.width - 100, 0, 100, 45);
    newdp.backgroundColor= UIColorFromRGB(0xDE3B30);
    [newdp setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [newdp setTitle:@"支付" forState:UIControlStateNormal];
    [newdp addTarget:self action:@selector(bottomClickEvent:) forControlEvents:UIControlEventTouchUpInside];
    [_bottomToolView addSubview:newdp];
    
    _lbPrice = [[TTTAttributedLabel alloc] initWithFrame:CGRectMake(PHOTO_FRAME_WIDTH, 0, 200, 45)];
    _lbPrice.backgroundColor = [UIColor clearColor];
    _lbPrice.font = FONT(18);
  //  _lbPrice.textColor = [UIColor blackColor];//RED_COLOR;
    [_bottomToolView addSubview:_lbPrice];
    
    _helpDp =[UIButton buttonWithType:UIButtonTypeCustom];
    _helpDp.tag=1;
    _helpDp.frame =CGRectMake(_lbPrice.frame.size.width +_lbPrice.frame.origin.x+PHOTO_FRAME_WIDTH, (45-25)/2, 25, 25);
    _helpDp.backgroundColor=  UIColorFromRGB(0xe1e1e1);//[UIColor lightGrayColor];
    _helpDp.layer.cornerRadius = 25/2;
    _helpDp.layer.masksToBounds = YES;
    _helpDp.titleLabel.font = FONT(12);
    [_helpDp setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_helpDp setTitle:@"▲" forState:UIControlStateNormal];
    [_helpDp addTarget:self action:@selector(bottomClickEvent:) forControlEvents:UIControlEventTouchUpInside];
    [_bottomToolView addSubview:_helpDp];
    
    [self updateTotalFee:NO];
}
-(void)bottomClickEvent:(id)sender
{
    UIButton *btn =(UIButton*)sender;
    switch (btn.tag) {
        case 0:
        {
            if(_svmanger)
            {
                //如果有弹出帮助层，先关闭弹出层。
                [self bottomClickEvent:_helpDp];
            }
             [self addShopOrder];
        }
            break;
        case 1: //弹出信息
        {
            if (btn.isSelected) {
                [_helpDp setSelected:NO];
                 [_helpDp setTitle:@"▲" forState:UIControlStateNormal];
            }else{
                 [_helpDp setSelected:YES];
                 [_helpDp setTitle:@"▼" forState:UIControlStateNormal];
            }
            [self showDetailHelper:_helpDp.isSelected];
        }
            break;
        default:
            break;
    }
   
}
- (float) updateTotalFee:(NSInteger)type //1 余额 2 积分
{
 
    NSString *totalPrice =[[NSString stringWithFormat:@"%@",[_orderinfoDictionary objectForKey:@"totalPrice"]] replaceNullString];
    float fTotalFee = [totalPrice floatValue];//直接使用云端计算好的总费用，不用客户端的计算公式。客户端无法
    
    NSString *user_balance =[[NSString stringWithFormat:@"%@",[_userinfoDictionary objectForKey:@"user_balance"]] replaceNullString];
    NSString *jifen =[[NSString stringWithFormat:@"%@",[_userinfoDictionary objectForKey:@"score_dk_fee_max"]] replaceNullString];
    
    if(type ==1)
    {
        fTotalFee -= [user_balance floatValue];
         [_balanceSwitch setOn:YES animated:YES];
        [_jifenSwitch setOn:NO animated:YES];
    }else if(type ==2){
        [_jifenSwitch setOn:YES animated:YES];
        [_balanceSwitch setOn:NO animated:YES];
        fTotalFee -= [jifen floatValue];
    }
    if (self.dpCodeDictionary && [[self.dpCodeDictionary allKeys] containsObject:@"code_fee"])
    {
        CGFloat code_fee = [[self.dpCodeDictionary objectForKey:@"code_fee"] floatValue];
        fTotalFee -= code_fee;
    }
    if (fTotalFee<0) {
        fTotalFee = 0;
    }
    NSString* strTotalFee = [NSString stringWithFormat:@"总计:  ¥%.2f", fTotalFee];
   
    [_lbPrice setText:strTotalFee afterInheritingLabelAttributesAndConfiguringWithBlock:^ NSMutableAttributedString  *(NSMutableAttributedString *attributedString)
     {
         
         [attributedString addAttribute:NSFontAttributeName
                                  value:FONT(15)
                                  range:NSMakeRange(0,[attributedString length])];
         //设置字体颜色
         [attributedString addAttribute:(id)kCTForegroundColorAttributeName value:PRICE_LABEL_COLOR range:NSMakeRange(0,[attributedString length])];
         
         
         NSRange range = [[attributedString string] rangeOfString:@"¥"];
         if (range.location != NSNotFound)
         {
             
             NSRange rgDot = [[attributedString string] rangeOfString:@"."];
             if(rgDot.location != NSNotFound)
             {
                 range.length = rgDot.location - range.location;
                 [attributedString addAttribute:NSFontAttributeName value:FONT(21) range:range];
                 [attributedString addAttribute:(id)kCTForegroundColorAttributeName
                                          value:RED_COLOR
                                          range:range];
             }
             
         }
         
         CGFloat lineSpace = 1.0f;
         CTParagraphStyleSetting lineSpaceStyle;
         lineSpaceStyle.spec = kCTParagraphStyleSpecifierLineSpacingAdjustment;
         lineSpaceStyle.valueSize = sizeof(lineSpace);
         lineSpaceStyle.value =&lineSpace;
         
         //设置文本段间距
         CGFloat paragraphSpacing = 0.0f;
         CTParagraphStyleSetting paragraphSpaceStyle;
         paragraphSpaceStyle.spec = kCTParagraphStyleSpecifierParagraphSpacing;
         paragraphSpaceStyle.valueSize = sizeof(CGFloat);
         paragraphSpaceStyle.value = &paragraphSpacing;
         
         //创建设置数组
         CTParagraphStyleSetting settings[ ] ={lineSpaceStyle,paragraphSpaceStyle};
         CTParagraphStyleRef style = CTParagraphStyleCreate(settings ,2);
         
         //给文本添加设置
         [attributedString addAttribute:(id)kCTParagraphStyleAttributeName value:(id)CFBridgingRelease(style) range:NSMakeRange(0 , [attributedString length])];
         return attributedString;
         
     }];
    CGSize size = [_lbPrice boundingRectWithSize:CGSizeMake(DEVICE_WIDTH/2, 45)];
    _lbPrice.frame =CGRectMake(PHOTO_FRAME_WIDTH, 0, size.width, 45);
    _helpDp.frame =CGRectMake(_lbPrice.frame.size.width +_lbPrice.frame.origin.x+PHOTO_FRAME_WIDTH, (45-25)/2, 25, 25);
    return fTotalFee;
}

//=======================================================
// 获取用户积分
//=======================================================
-(void)getUserScore
{
    __weak typeof (self) wSelf = self;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:_orderInfo.strJson forKey:@"webjson"];
    [dict setValue:_orderInfo.webName forKey:@"siteName"];
    [dict setValue:_type forKey:@"type"];
    [OrderApi getUserScore:dict success:^(AFHTTPRequestOperation *operation, id result) {
        if (result&&[result isKindOfClass:[NSDictionary class]]) {
            NSDictionary *resultDist =(NSDictionary*)result;
           //
            id orderinfo = [resultDist objectForKey:@"order_info"];
            if (orderinfo && [orderinfo isKindOfClass:[NSDictionary class]]) {
                wSelf.orderinfoDictionary = [NSMutableDictionary dictionaryWithDictionary:orderinfo];
            }
            //
            id userinfo = [resultDist objectForKey:@"user_info"];
            if (userinfo && [userinfo isKindOfClass:[NSDictionary class]]) {
                wSelf.userinfoDictionary = [NSMutableDictionary dictionaryWithDictionary:userinfo];
            }
            //
            id aggremt = [resultDist objectForKey:@"agreement"];
            if (aggremt && [aggremt isKindOfClass:[NSDictionary class]]) {
                wSelf.agreementinfoDictionary = [NSMutableDictionary dictionaryWithDictionary:aggremt];
            }
            //
            //
//            NSLog(@"%@",resultDist);
            [wSelf updateTotalFee:0];
            [_tbView reloadData];
        }
    } failure:^(NSError *error) {
      
    }];
}
//=======================================================
// 默认地址
//=======================================================
-(void)getDefaultaddress
{
    [ZShare showAnimationView:self.view center:CGPointZero];
    NSMutableDictionary *dict =[NSMutableDictionary dictionary];
    [dict setValue:_type forKey:@"type"];
    __weak typeof (self) wSelf = self;
    [OrderApi getDefaultAddress:dict success:^(AFHTTPRequestOperation *operation, id result) {
        if (result&&[result isKindOfClass:[NSDictionary class]]) {
            NSDictionary *resultDist =(NSDictionary*)result;
//            NSLog(@"%@",resultDist);
            id data =  [resultDist objectForKey:@"row"];
            if (data && [data isKindOfClass:[NSDictionary class]]){
                _addressDictionary =[NSMutableDictionary dictionaryWithDictionary:data] ;
                [ZShare sharedInstance].defaultAddress=_addressDictionary;
            }else
            {
                [ZShare sharedInstance].defaultAddress=nil;
                _addressDictionary =nil;
            }
            [_tbView reloadData];
        }
        [ZShare hiddenAnimationView:wSelf.view];
    } failure:^(NSError *error) {
        [ZShare hiddenAnimationView:wSelf.view];
    }];
}

//=================================================
// 提交订单
//=================================================

-(NSString*)good_info
{
    
    NSMutableDictionary *infod = [NSMutableDictionary dictionary];
    [infod setValue:[NSString stringWithFormat:@"%.0f",self.orderInfo.fPrice] forKey:@"good_fee"];
    [infod setValue:self.orderInfo.strProductImageURL forKey:@"good_img"];
    [infod setValue:self.orderInfo.strProduct forKey:@"good_name"];
    [infod setValue:self.orderInfo.strDim forKey:@"good_intro"];
    [infod setValue:self.orderInfo.strSkuID forKey:@"goods_sn"];
    [infod setValue:self.orderInfo.webUrl forKey:@"goods_url"];
    [infod setValue:self.orderInfo.strPa forKey:@"goods_pa"];
    [infod setValue:self.orderInfo.webName forKey:@"goods_from"];
    NSString *goodinfo = [ZShare DataTOjsonString:infod];
    
    return goodinfo;
}
-(NSString*)order_info
{
    NSString *totalPrice =[[NSString stringWithFormat:@"%@",[_orderinfoDictionary objectForKey:@"totalPrice"]] replaceNullString];
     NSString *dimsInfo =[[NSString stringWithFormat:@"%@",[_orderinfoDictionary objectForKey:@"dimsInfo"]] replaceNullString];
     NSString *conversionFee =[[NSString stringWithFormat:@"%@",[_orderinfoDictionary objectForKey:@"conversionFee"]] replaceNullString];
     NSString *qty =[[NSString stringWithFormat:@"%@",[_orderinfoDictionary objectForKey:@"qty"]] replaceNullString];
     NSString *shipFeeLocal =[[NSString stringWithFormat:@"%@",[_orderinfoDictionary objectForKey:@"shipFeeLocal"]] replaceNullString];
     NSString *shipFeeOverseas =[[NSString stringWithFormat:@"%@",[_orderinfoDictionary objectForKey:@"shipFeeOverseas"]] replaceNullString];
     NSString *taxPrice =[[NSString stringWithFormat:@"%@",[_orderinfoDictionary objectForKey:@"taxPrice"]] replaceNullString];
     NSString *weightKg =[[NSString stringWithFormat:@"%@",[_orderinfoDictionary objectForKey:@"weightKg"]] replaceNullString];
     NSString *weightUnit =[[NSString stringWithFormat:@"%@",[_orderinfoDictionary objectForKey:@"weightUnit"]] replaceNullString];
    NSString *price =[[NSString stringWithFormat:@"%@",[_orderinfoDictionary objectForKey:@"price"]] replaceNullString];
    NSMutableDictionary *infod = [NSMutableDictionary dictionary];
    [infod setValue:dimsInfo forKey:@"order_intro"];
    [infod setValue:shipFeeLocal forKey:@"order_freight"];
    [infod setValue:taxPrice forKey:@"order_tariff"];
    [infod setValue:price forKey:@"order_productprice"];
    [infod setValue:qty forKey:@"order_productnum"];
    [infod setValue:shipFeeOverseas forKey:@"order_USAfreight"];
    [infod setValue:weightKg forKey:@"order_productpounds"];
    [infod setValue:weightUnit forKey:@"order_productweightunit"];
    [infod setValue:conversionFee forKey:@"order_conversionFee"];
    [infod setValue:totalPrice forKey:@"totalPrice"];
    //
    //备注\折扣券\积分
    [infod setValue:[NSString stringWithFormat:@"%@",self.txtBeizhu.text] forKey:@"order_beizhu"];
     NSString *coupon = [[ZShare sharedInstance].zhekouquan replaceNullString];
    if(coupon && coupon.length>0)
    {
        [infod setValue:[NSString stringWithFormat:@"%@",coupon] forKey:@"order_zhekouquan"];
    }else{
        [infod setValue:@"" forKey:@"order_zhekouquan"];
    }
  
    NSString *user_balance =[[NSString stringWithFormat:@"%@",[_userinfoDictionary objectForKey:@"user_balance"]] replaceNullString];
    NSString *jifen =[[NSString stringWithFormat:@"%@",[_userinfoDictionary objectForKey:@"score_dk_fee_max"]] replaceNullString];
    if ([_zhekouquanSwitch isOn])  {
        [infod setValue:@"1" forKey:@"order_zhekouquanyuanjia"];
    }else{
        [infod setValue:@"0" forKey:@"order_zhekouquanyuanjia"];
    }
    if ([_balanceSwitch isOn])  {
        [infod setValue:user_balance forKey:@"order_balance"];
    }else{
        [infod setValue:@"0" forKey:@"order_balance"];
    }
    if ([_jifenSwitch isOn]) {
        [infod setValue:jifen forKey:@"order_jifen"];
    }else{
        [infod setValue:@"0" forKey:@"order_jifen"];
    }
    //
    [infod addEntriesFromDictionary:_orderinfoDictionary];
    NSString *orderinfo = [ZShare DataTOjsonString:infod];
    return orderinfo;
}
-(void)addShopOrder
{
    NSString *addressid = [_addressDictionary objectForKey:@"id"];
    if (addressid.length==0) {
        [[ZToastManager ShardInstance] showtoast:@"请添加收件人地址！"];
        return;
    }
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
    [dictionary setValue:addressid forKey:@"shop_address_id"];
    if (self.orderInfo.strProduct.length==0) {
        [dictionary setValue:self.orderInfo.strDim forKey:@"subject"];
    }else{
        [dictionary setValue:self.orderInfo.strProduct forKey:@"subject"];
    }
    
    [dictionary setValue:@"1" forKey:@"pay_type"];
    [dictionary setValue:_type forKey:@"type"];
    
    if (self.orderInfo.strDim.length==0) {
        [dictionary setValue:self.orderInfo.strProduct forKey:@"body"];
    }else{
        [dictionary setValue:self.orderInfo.strDim forKey:@"body"];
    }
    //
    NSString *total_fee =[[NSString stringWithFormat:@"%@",[_orderinfoDictionary objectForKey:@"totalPrice"]] replaceNullString];
    [dictionary setValue:total_fee forKey:@"total_fee"];
    if ([_balanceSwitch isOn]) {
        [dictionary setValue:@"2" forKey:@"dk_type"];
        NSString *user_balance =[[NSString stringWithFormat:@"%@",[_userinfoDictionary objectForKey:@"user_balance"]] replaceNullString];
        float balance = [user_balance floatValue];
        float totalprice = [total_fee floatValue];
        
        NSString *dk_fee=@"0";
        if (balance>=totalprice) {
            dk_fee = [NSString stringWithFormat:@"%.0f",totalprice];
        }else{
            dk_fee = user_balance;
        }
        [dictionary setValue:dk_fee forKey:@"dk_fee"];
    }else if ([_jifenSwitch isOn])
    {
        [dictionary setValue:@"1" forKey:@"dk_type"];
        NSString *jifen =[[NSString stringWithFormat:@"%@",[_userinfoDictionary objectForKey:@"score_dk_fee_max"]] replaceNullString];
        [dictionary setValue:jifen forKey:@"dk_fee"];
    }
    //
    if (self.dpCodeDictionary && [[self.dpCodeDictionary allKeys] containsObject:@"order_dp_code"]) {
        NSString *order_dp_code = [self.dpCodeDictionary stringForKey:@"order_dp_code" withDefaultValue:@""];
        [dictionary setValue:order_dp_code forKey:@"order_dp_code"];//优惠券
    }else{
        [dictionary setValue:@"" forKey:@"order_dp_code"];//优惠券
    }
    
    if (self.dpCodeDictionary && [[self.dpCodeDictionary allKeys] containsObject:@"code_fee"])
    {
        NSString *code_fee =[[NSString stringWithFormat:@"%@",[self.dpCodeDictionary objectForKey:@"code_fee"]] replaceNullString];
        [dictionary setValue:code_fee forKey:@"code_fee"];
    }
    //
    NSString *price =[[NSString stringWithFormat:@"%@",[_orderinfoDictionary objectForKey:@"price"]] replaceNullString];
    [dictionary setValue:price forKey:@"price"];
   
    [dictionary setValue:[NSString stringWithFormat:@"%d",self.orderInfo.nQty] forKey:@"num"];
    [dictionary setValue:[self good_info] forKey:@"goods_info"];
    [dictionary setValue:[self order_info] forKey:@"order_info"];
    
    if ([self isZhiFu]) {
        NSString *out_trade_no =[[NSString stringWithFormat:@"%@",[_zhifuDictionary objectForKey:@"out_trade_no"]] replaceNullString];
        NSString *total_fee =[[NSString stringWithFormat:@"%@",[_zhifuDictionary objectForKey:@"total_fee"]] replaceNullString];
        [dictionary setValue:out_trade_no forKey:@"out_trade_no"];
        [dictionary setValue:total_fee forKey:@"total_fee"];
        [self alipay:dictionary];
        return;
    }else
    {
        [[ZToastManager ShardInstance] showprogress];
        __weak typeof (self) wSelf = self;
        [OrderApi addShopOrder:dictionary success:^(AFHTTPRequestOperation *operation, id result) {
            [[ZToastManager ShardInstance] hideprogress];
            if (result&&[result isKindOfClass:[NSDictionary class]]) {
                NSDictionary *resultDist =(NSDictionary*)result;
                _zhifuDictionary = [NSMutableDictionary dictionaryWithDictionary:resultDist];
                
//                NSLog(@"%@",resultDist);
                int code =[[resultDist objectForKey:@"code"] intValue];
                if (code==1) {
                  
                    [dictionary setValue:[resultDist objectForKey:@"out_trade_no"] forKey:@"out_trade_no"];
                    [dictionary setValue:[resultDist objectForKey:@"total_fee"] forKey:@"total_fee"];
                    [dictionary setValue:[resultDist objectForKey:@"body"] forKey:@"body"];
                    if ([wSelf isZhiFu]) {
                         [wSelf alipay:dictionary];
                    }
                }else{
                    [[ZToastManager ShardInstance] showtoast:[resultDist objectForKey:@"msg"]];
                }
                
            }
            [ZShare hiddenAnimationView:wSelf.view];
        } failure:^(NSError *error) {
            [[ZToastManager ShardInstance] hideprogress];
            [ZShare hiddenAnimationView:wSelf.view];
        }];
    }
}
//=================================================
// 订单提交成功判断支付信息
//返回值 json
//{
//    'code' => 1,
//    'msg' => '订单保存成功',
//    'add_time' => $add_time,
//    'total_fee' => $total_fee,
//    'out_trade_no' => $param['out_trade_no'],
//    'encryption' => md5($param['out_trade_no'] . $_SESSION['user_id'] . $total_fee . $Keys . $add_time),
//    'md5str' => $param['out_trade_no'] . $_SESSION['user_id'] . $total_fee . $Keys . $add_time,
//}
// key @"chrdwHDHXT12345ssdlh";
//=================================================
-(BOOL)isZhiFu
{
    if (_zhifuDictionary==nil || ![[_zhifuDictionary allKeys] containsObject:@"out_trade_no"]) {
        return NO;
    }
    //添加订单后支付
    NSString *add_time =[[NSString stringWithFormat:@"%@",[_zhifuDictionary objectForKey:@"add_time"]] replaceNullString];
    NSString *total_fee =[[NSString stringWithFormat:@"%@",[_zhifuDictionary objectForKey:@"total_fee"]] replaceNullString];
    NSString *out_trade_no =[[NSString stringWithFormat:@"%@",[_zhifuDictionary objectForKey:@"out_trade_no"]] replaceNullString];
    NSString *encryption =[[NSString stringWithFormat:@"%@",[_zhifuDictionary objectForKey:@"encryption"]] replaceNullString];
    NSString *md5str = [NSString stringWithFormat:@"%@%@%@chrdwHDHXT12345ssdlh%@",out_trade_no,[ZShare sharedInstance].getUserId,total_fee,add_time];
    md5str = [ZShare md5:md5str];
    if ([md5str isEqualToString:encryption]) {
        return YES;
    }
    return NO;
}


//=================================================
// 支付宝支付处理
//=================================================
-(void)alipay:(NSDictionary*)dict
{
    [UMengShare event:CK_GOZHIFU acc:1];
    NSString *totalfee =[[NSString stringWithFormat:@"%@",[dict objectForKey:@"total_fee"]] replaceNullString];
    if ([totalfee floatValue]==0) {
        NSString *out_trade_no =[[NSString stringWithFormat:@"%@",[dict objectForKey:@"out_trade_no"]] replaceNullString];
        OrderDetailViewController *orderDetail =[[OrderDetailViewController alloc] init];
        orderDetail.out_trade_no = out_trade_no;
        orderDetail.from =@"trade";
        [self.navigationController pushViewController:orderDetail animated:YES];
        orderDetail=nil;
        return;
    }
    
    NSString *tradeNO = [dict objectForKey:@"out_trade_no"]; //订单ID（由商家自行制定）
    NSString *productName = [dict objectForKey:@"subject"]; //商品标题
    NSString *productDescription =[[NSString stringWithFormat:@"%@",[dict objectForKey:@"body"]] replaceNullString]; //商品描述
    if (productDescription.length==0 || [productDescription isEqualToString:@" "]) {
        productDescription = productName;
    }
    NSString *amount = [dict objectForKey:@"total_fee"];; //商品价格
    AppDelegate *app = [[UIApplication sharedApplication]delegate];
    app.orderDelegate=self;
    __weak typeof (self) wSelf = self;
    [AlipayRequestConfig alipayWithTradeNO:tradeNO productName:productName productDescription:productDescription amount:amount callback:^(NSDictionary *resultDic) {
        [wSelf orderPayOK:resultDic];
    }];
}
-(void)orderPayOK:(id)info
{
    NSDictionary *resultDic =(NSDictionary *)info;
    
    NSString *memo = [resultDic objectForKey:@"memo"];
    [[ZToastManager ShardInstance] showtoast:memo];
    NSString *resultStatus = [resultDic objectForKey:@"resultStatus"];
    if ([resultStatus isEqualToString:@"9000"]) {
    
        NSMutableDictionary *dcit =[NSMutableDictionary dictionary];
        if ([self.jifenSwitch isOn]) {
            NSString *jifen =[[NSString stringWithFormat:@"%@",[_userinfoDictionary objectForKey:@"score_dk_fee_max"]] replaceNullString];
            [dcit setValue:jifen forKey:@"rmb"];
        }
        if ([self.balanceSwitch isOn]) {
            NSString *user_balance =[[NSString stringWithFormat:@"%@",[_userinfoDictionary objectForKey:@"user_balance"]] replaceNullString];
            [dcit setValue:user_balance forKey:@"balance"];
        }
        [dcit setValue:[ZShare DataTOjsonString:resultDic] forKey:@"return_data"];
        [OrderApi alipayReturnUrl:dcit success:^(AFHTTPRequestOperation *operation, id result) {
//            NSLog(@"%@",result);
        } failure:^(NSError *error) {
            
        }];
        NSString *out_trade_no =[[NSString stringWithFormat:@"%@",[_zhifuDictionary objectForKey:@"out_trade_no"]] replaceNullString];
        OrderDetailViewController *orderDetail =[[OrderDetailViewController alloc] init];
        orderDetail.out_trade_no = out_trade_no;
        orderDetail.from =@"trade";
        [self.navigationController pushViewController:orderDetail animated:YES];
        orderDetail=nil;
    }else  if ([resultStatus isEqualToString:@"6001"])
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"支付状态" message:@"是否确定取消支付？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert show];
        alert=nil;
    }
}


-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
        {
            AppDelegate *app = [[UIApplication sharedApplication]delegate];
            app.orderDelegate=nil;
        }
            break;
        case 1:
        {
            AppDelegate *app = [[UIApplication sharedApplication]delegate];
            app.orderDelegate=nil;
            if (self.navigationController) {
                if (self.navigationController.viewControllers.count == 1) {
                    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
                } else {
                    [self.navigationController popViewControllerAnimated:YES];
                }
            } else {
                [self dismissViewControllerAnimated:YES completion:nil];
            }
        }
            break;
        default:
            break;
    }
}
//======================================================
//?帮助提醒
//======================================================
-(void)clickHelpEvent:(NSString *)str
{
    NSString *helpstr =@"";
    if ([str isEqualToString:@"1"]) {
        helpstr = [_agreementinfoDictionary objectForKey:@"help_title"];
    }else if ([str isEqualToString:@"3"]) {
        helpstr = [_agreementinfoDictionary objectForKey:@"help_score"];
    }else  if ([str isEqualToString:@"4"]) {
        helpstr = [_agreementinfoDictionary objectForKey:@"help_overseas"];
    }else if ([str isEqualToString:@"2"])
    {
        
        [self bottomClickEvent:_helpDp];
        return;
    }else  if ([str isEqualToString:@"5"]) {
        helpstr = @"如果折扣码无效，并且，您不希望原价下单，我们将取消该订单，并全额退款到您的账户。";
    }
    if (helpstr.length==0) {
        return;
    }
    // one button
    [QKInfoCard showOneButtonWithTitle:@"" Message:helpstr ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"好的" Click:^{
        NSLog(@"click0");
    }];
}

-(void)initPriceListView
{

    
    if (!_svmanger)
    {
        _svmanger = [[UIView alloc]init];
        _svmanger.backgroundColor =  [UIColor colorWithRed:0.11 green:0.11 blue:0.11 alpha:0.6];
        
        UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(MaskViewTapped:)];
        [_svmanger addGestureRecognizer:tapGestureRecognizer];
        tapGestureRecognizer=nil;
        
    }
    
    _svmanger.frame = self.view.bounds;
    [self.view addSubview:_svmanger];
    
    _svmanger.alpha = 0;
    // Animate In
    [UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationOptionCurveEaseIn animations:^{
        _svmanger.alpha = 0.6;
    }
                     completion:^(BOOL finished)
     {

     }];
    
    
    if(!_priceListView)
    {
        OrderPriceListView *priceListView =[[OrderPriceListView alloc] initWithFrame:CGRectMake(0,self.view.frame.size.height, self.view.frame.size.width, self.view.frame.size.height/2)];
        id help_price = [_agreementinfoDictionary objectForKey:@"help_price"];
        if (help_price && [help_price isKindOfClass:[NSArray class]]) {
            priceListView.itemDatas = [NSMutableArray arrayWithArray:help_price];
        }
    
        _priceListView = priceListView;
        priceListView = nil;
    }
    
    [self.view addSubview:_priceListView];
    
    
    
    // Animate In
    [UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationOptionCurveEaseIn animations:^{
        _priceListView.frame = CGRectMake(0, self.view.bounds.size.height/2 , self.view.bounds.size.width,  self.view.bounds.size.height/2  - self.bottomToolView.frame.size.height);
        
    }
    completion:^(BOOL finished)
    {
      //  if (finished)
      //  {

       // }
    }];
    
    
//    [_svmanger slideViewIn];
}


- (void) MaskViewTapped:(UITapGestureRecognizer*) tap
{
    [self bottomClickEvent:_helpDp];
    
}
-(void)showDetailHelper:(BOOL)isShow
{
    if(isShow == YES)
    {
        [self initPriceListView];
        
        [self.view bringSubviewToFront: self.bottomToolView ];

    }else
    {
      //  [_svmanger slideViewIn];
        
   //     [_svmanger slideViewOut];
        [UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationOptionCurveEaseIn animations:^{
            _svmanger.alpha = 0.0;
            _priceListView.frame = CGRectMake(0,self.view.frame.size.height, self.view.frame.size.width, self.view.frame.size.height/2);
        }
                         completion:^(BOOL finished)
         {
             if(_svmanger)
             {
                 [_svmanger removeFromSuperview];
                 _svmanger = nil;
             }
             
             
             if(_priceListView)
             {
                 [_priceListView removeFromSuperview];
                 _priceListView = nil;
             }
         }];

    }
    
    
}
//
@end
